<?php
namespace app\api\controller;
use think\Cache;
use think\Controller;
use think\Request;
use think\Db;
use think\Loader;
header("Content-type:text/html;charset=utf-8");
Loader::import('Wxpay.Wxpay.WxPay', EXTEND_PATH, '.Api.php');//将附件放入根目录下的/extend
Loader::import('Wxpay.Wxpay.WxPay', EXTEND_PATH, '.Config.php');//将附件放入根目录下的/extend
class Openid extends Controller
{

  //获取内容
  protected $config;
  public function _initialize()
  {
    $config=new \WxPayConfig();
    $this->config=$config->_config;
  }

  //用户id
  public function id(){
    $uid = db('user')->where('code',input('openid'))->value('uid');
    return $this->AjaxReturn(1,'操作成功',$uid);
  }


  //获取微信登录用户信息
  public function openid()
  {
    $array=array();
    $appid = input('appid');
    $appsecret = input('appsecret');
    $code = input('code');
    $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$appsecret&js_code=$code&grant_type=authorization_code";
    $weixin = file_get_contents($url);//通过code换取网页授权access_token
    $jsondecode = json_decode($weixin); //对JSON格式的字符串进行编码
    $array = get_object_vars($jsondecode);//转换成数组
    $a=db('user')->where('code',$array['openid'])->find();
    if(!$a){
      $res = Db::name('user')->insert([
        'code'=>$array['openid'],
        'nickname'=>'无名',
        'uflg'=>1,
        'gflg'=>0,
        "avatars_img" => '',
        "phone" => '',
        'uname' => '',
        "company" => ''
      ]);
    }
    return $array['openid'];
  }

  /* 微信支付完成，回调地址url方法  xiao_notify_url() */
  public function xiao_notify_url(){
    $pers=time();
    $xml=file_get_contents("php://input");
    $data = $this->xml_to_array($xml);//微信支付成功，返回回调地址url的数据：XML转数组Array
    $postSign = $data['sign'];
    unset($data['sign']);
    $result = $data;
    ksort($data);// 对数据进行排序

    $str1 = $this->sign($data);//对数组数据拼接成key=value字符串
    $user_sign = strtoupper(md5($str1));   //再次生成签名，与$postSign比较

    $openid = $data['openid'];
    $uid=db('user')->where('code',$openid)->field('uid')->find();
    $total_fee = ($data['total_fee']);
    $where['number'] = $data['out_trade_no'];
    $order_status = db('pay')->where($where)->find();
    if(($data['return_code']=='SUCCESS') && ($data['result_code'] == 'SUCCESS')){
      /*
           * 首先判断，订单号是否匹配成功
           * 其次，订单已经为ok的，直接返回SUCCESS
           * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
           */
      if($order_status['flg']=='已支付'){
        if ($result) {
          $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
          file_put_contents(ROOT_PATH . '/upload' . DS . 'zhifu' . $pers, $result);
          $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
      }else {
        $tid=db('package')->where('price',$total_fee/100)->find();
        db('pay')
          ->where('number', $order_status['number'])
          ->update(['flg' => '已支付']);
        db('real')
          ->where('uid',$uid['uid'])
          ->update(['tid' => $tid['tid']]);
        if ($order_status) {
          $taocan = db('real')
            ->join('f_package', 'f_real.tid=f_package.tid','left')
            ->where('f_real.uid', $uid['uid'])
            ->field('f_package.phase_time')
            ->find();//查询套餐日期
          $stoptime=date('Y-m-d H:i:s',strtotime('+'.$taocan['phase_time'].' month'));
          // db('real')->update([
          // 'starttime'=>date('Y-m-d H:i:s'),
          // 'stoptime' => $stoptime
          //]);
        } else {
          file_put_contents(ROOT_PATH . '/upload' . DS . 'xiugai' . $pers, $order_status);//
          $result = false;
        }
      }
    }else {
      file_put_contents(ROOT_PATH.'/upload'.DS.'cuowu'.$pers,$xml);
      $result = false;
    }
    if ($result) {
      $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
    }else{
      $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
      file_put_contents(ROOT_PATH . '/upload' . DS . 'nosign' . $pers,$result);
    }

    echo $str;
    exit();
    //return $result;
  }
  /* 微信支付完成，回调地址url方法  notify_url() */
  public function notify_url(){
    $pers=time();
    $xml=file_get_contents("php://input");
    $data = $this->xml_to_array($xml);//微信支付成功，返回回调地址url的数据：XML转数组Array
    $postSign = $data['sign'];
    unset($data['sign']);
    $result = $data;
    ksort($data);// 对数据进行排序

    $str1 = $this->sign($data);//对数组数据拼接成key=value字符串
    $user_sign = strtoupper(md5($str1));   //再次生成签名，与$postSign比较

    $openid = $data['openid'];
    $uid=db('user')->where('code',$openid)->field('uid')->find();
    $total_fee = ($data['total_fee']);
    $where['number'] = $data['out_trade_no'];

    $order_zixun=db('zpay')->where($where)->find();
    if(($data['return_code']=='SUCCESS') && ($data['result_code'] == 'SUCCESS')){
      /*
           * 首先判断，订单号是否匹配成功
           * 其次，订单已经为ok的，直接返回SUCCESS
           * 最后，订单没有为ok的，更新状态为ok，返回SUCCESS
           */
      if($order_zixun['flg']=='已支付'){
        if($result) {
          $str = '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
          file_put_contents(ROOT_PATH . '/upload' . DS . 'nozhifu' . $pers, $result);
        }
        echo $str;
        exit();
      }else {
        if ($order_zixun) {
          db('zpay')
            ->where('number', $order_zixun['number'])
            ->update(['flg' => '已支付']);
        } else {
          file_put_contents(ROOT_PATH . '/upload' . DS . 'noxiugai' . $pers, $order_zixun);
          $result = false;
        }
      }
    }else {
      file_put_contents(ROOT_PATH.'/upload'.DS.'cuowu'.$pers,$result);
      $result = false;
    }
    if ($result) {
      $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
    }else{
      file_put_contents(ROOT_PATH . '/upload' . DS . 'nosuccess' . $pers, $result);
      $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
    }
    echo $str;
    exit();
    //return $result;
  }
  //签名
  private function sign($data){
    $keys=$this->config['KEY'];
    //步骤一：按字典序排列参数
    ksort($data);
    $buff='';
    foreach ($data as $k=>$v) {
      if($k!="sign"&&$v!=""&&!is_array($v)){
        $buff.=$k."=".$v."&";
      }
    }
    $buff=trim($buff,"&");
    //步骤二：在string后面贾$key
    $string=$buff. "&key=".$keys;
    //步骤三：md5加密
    $string=md5($string);
    //步骤四：所有字符转化为大写
    $sign=strtoupper($string);
    //dump($sign);
    return $sign;
  }

  /*
     * 不知道是啥
     *
     */
  private function xml_to_array($xml){
    //将XML转为array 禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    //simplexml_load_string()解析读取xml数据，然后转成json格式
    $result = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $result;
  }
  //详细页面的查看
  public function chakan()
  {
    $openid=input('openid');
    $data = Db::name('user')->where('code',$openid)->find();
    $openid=$data['uid'];
    $mid=input('mid');//接收文章mid
    $uid=input('uid');//接收文章发布人地uid
    //获取当前域名
    $request = Request::instance();
    $domain=$request->domain();
    if(!empty($mid))
    {
      $list = Db::name("message")
        ->alias('me')
        ->where('mid',$mid)
        ->join('f_real re','re.uid=me.uid','left')
        ->join('f_user us','us.uid=re.uid','left')
        ->field('me.mid,me.price,me.number,me.unit,me.address,us.uname,us.nickname,me.createtime,me.picture,me.content,us.company,us.phone,me.num,me.id,us.gflg,me.uid,me.title,re.rflg')->find();//print_r($list);die;
      //dump($list);die;
      if($list['rflg']==1)
      {
        $list['nickname']=$list['uname'];
      }
      if($list['unit']==1)
      {
        $list['unit']='吨';
      }
      elseif($list['unit']==2)
      {
        $list['unit']='公斤';
      }
      elseif($list['unit']==3)
      {
        $list['unit']='斤';
      }
      else
      {
        $list['unit']='个';
      }

      //图片加空
      $url=$domain.'/upload/message/';
      if($list['picture']!='')
      {
        $img=array_filter(explode(',',$list['picture']));
        foreach ($img as $key=>$value9)
        {
          $lis[]=$url.$value9;
        }
        //print_r($lis);die;
        $list['picture']=$lis;
      }
      else
      {
        $list['picture']=array($url.'no.jpg');
      }
      //查询是否关注追加到fans字段
      $fen=db('fans')->where('uid',$uid)->find();
      $arr=array_filter(explode(',',$fen['fuid']));
      //return 'uid'.$openid.'kong'.$fen['fuid'];die;
      if(in_array($openid,$arr))
      {
        $list['fans']=1;
      }
      else
      {
        $list['fans']=0;
      }
      //判断是不是我发表地文章
      if($openid==$uid)
      {
        $list['fans']=2;
      }
      //查询我又没有点赞这篇文章
      $dian=db('message')->where('mid',$mid)->field('id')->find();
      $arr1=array_filter(explode(',',$dian['id']));
      //return $openid.'->'.$dian['id'];die;
      if(in_array($openid,$arr1))
      {
        $list['dian']=1;
      }
      else
      {
        $list['dian']=0;
      }
      //计算点赞数量
      $num=array();
      $num=array_filter(explode(',',$list['id']));
      $list['id']=count($num);
      //计算评论数量
      $cha=db('evalute')->where('message_id',$mid)->where('bpid',0)->select();
      $list['num2']=count($cha);
      //print_r($num);die;
      //点赞的人
      if($list['id']!=0)
      {
        for($i=0;$i<count($num);$i++)
        {
          $diannum[]=db('user')->where('uid',$num[$i])->field('uid,uname,nickname')->find();
          $j=db('real')->where('uid',$num[$i])->find();
          if($j['rflg'] != 1)
          {
            $diannum[$i]['uname']=$diannum[$i]['nickname'];
          }
        }
      }
      else
      {
        //like点赞是不是为空
        $diannum=array();
      }

      //浏览加一
      $cha=db('message')->where('mid',$mid)->field('num')->find();
      $num=$cha['num']+1;
      $jia=db('message')->where('mid',$mid)->update(['num'=>$num]);
      //return $this->AjaxReturn("1","浏览数添加成功！");

      /* $data='';
             foreach ($dian as $value)
             {
                 $data.=$value['uname'].',';
             }
             $data=substr($data,0,strlen($data)-1);*/
      //print_r($data);die;
      //print_r($diannum);die;
      $list['like']=$diannum;//var_dump($list);die;//print_r($list);die;
      //$arrr=array_merge($list,$lis);//数组合并

      $bjid=db('message')->where('mid',$mid)->field('f_message.uid')->find();
      //判断是否认证&是否是官方账号
      $a=db('real')->join('f_user us','us.uid=f_real.uid')->where('f_real.uid',$openid)->field('f_real.rflg,us.gflg')->find();
      //查询后台设置的转发次数限制
      $shezhi=db('shezhi')->where('zid',1)->field('userwenzhang,vipwenzhang,userbohao,vipbohao,userzhuanfa,vipzhuanfa')->find();
      $timestart=date("Y-m-d 00:00:00");
      $timeend=date("Y-m-d H:i:s");
      $shu=db('zhuanfa')
        ->where('zfid',$openid)
        ->where('f_zhuanfa.z_createtime','between',[$timestart,$timeend])
        ->count();//今日拨号
      if($data['phone']==''){
        $list['code'] = -2;
      }
      //官方账号无限制
      $list['myuid'] = $data['uid'];
      if($a['gflg']==1)
      {
        $list['shu']=$shu;
        $list['zhuan']=99999;
        return $this->AjaxReturn("1","操作成功",$list);
      }
      else
      {
        if($a['rflg']==1)
        {
          $list['shu']=$shu;
          $list['zhuan']=$shezhi['vipzhuanfa'];
          $list['a']=$a['rflg'];
          $a=Db::name('real')->where('uid',$openid)->field('tid')->find();
          $list['tid']=$a['tid'];
          return $this->AjaxReturn("1","操作成功",$list);
        }
        else
        {
          $list['shu']=$shu;
          $list['zhuan']=$shezhi['userzhuanfa'];
          $list['a']=$a['rflg'];
          $a=Db::name('real')->where('uid',$openid)->field('tid')->find();
          $list['tid']=$a['tid'];
          return $this->AjaxReturn("1","操作成功",$list);
        }
      }


    }
    else
    {
      return $this->AjaxReturn("-1","未接收到文章mid");
    }
  }

  //短信验证码的发送
  public function sendTemplateSMS()
  {
    $openid = request()->post('openid');
    if ($openid == null) {
      $this->AjaxReturn(-1, "用户信息错误！");
    }
    else
    {
      $data = Db::name('user')->where('code', $openid)->find();
      if (empty($data)) {
        $res = Db::name('user')->insert([
          'code' => $openid,
          'uflg' => 1,
          'gflg' => 0,
          "avatars_img" => '',
          "phone" => '',
          'uname' => '',
          "company" => ''
        ]);
      }
    }
    //$to,$datas,$tempId
    //$openid=$this->uid;//openid
    $to=input('phone');
    $a=rand(10000,99999);//5位数字随机生成
    $datas=array($a,'5');
    Cache::set($to,$a,600);//缓存存在10分钟
    //$huan=Cache::get($to);
    //return $a;die;
    $tempId="419959";
    vendor('duanxin.CCPRestSmsSDK');

    //sendTemplateSMS($to,array('5556','5'),"1");//手机号码，替换内容数组，模板ID
    //主帐号,对应开官网发者主账号下的 ACCOUNT SID
    $accountSid= '8a216da8555d110e015571b1f40519a5';
    //主帐号令牌,对应官网开发者主账号下的 AUTH TOKEN
    $accountToken= 'dc82f19888114fe6863a75ac3c476487';
    //应用Id，在官网应用列表中点击应用，对应应用详情中的APP ID
    //在开发调试的时候，可以使用官网自动为您分配的测试Demo的APP ID
    $appId='8a216da8555d110e015571b1f53319ab';
    //请求地址
    //沙盒环境（用于应用开发调试）：sandboxapp.cloopen.com
    //生产环境（用户应用上线使用）：app.cloopen.com
    $serverIP='app.cloopen.com';
    //请求端口，生产环境和沙盒环境一致
    $serverPort='8883';
    //REST版本号，在官网文档REST介绍中获得。
    $softVersion='2013-12-26';
    // 初始化REST SDK
    //global $accountSid,$accountToken,$appId,$serverIP,$serverPort,$softVersion;
    $rest = new \REST($serverIP,$serverPort,$softVersion);
    $rest->setAccount($accountSid,$accountToken);
    $rest->setAppId($appId);

    // 发送模板短信
    echo "Sending TemplateSMS to $to <br/>";
    $result = $rest->sendTemplateSMS($to,$datas,$tempId);
    /*if($result == NULL ) {
            echo "result error!";
            break;
        }*/

    if($result->statusCode!=0) {
      echo "error code :" . $result->statusCode . "<br>";
      echo "error msg :" . $result->statusMsg . "<br>";
      //TODO 添加错误处理逻辑
      return $this->AjaxReturn("-1", "发送失败！");
    }else{
      echo "Sendind TemplateSMS success!<br/>";
      // 获取返回信息
      $smsmessage = $result->TemplateSMS;
      echo "dateCreated:".$smsmessage->dateCreated."<br/>";
      echo "smsMessageSid:".$smsmessage->smsMessageSid."<br/>";
      //TODO 添加成功处理逻辑
      return $this->AjaxReturn("1", "发送成功！");
    }

  }

  //修改手机号
  public function phone()
  {
    $openid=input('openid');
    $cha=db('user')->where('code',$openid)->field('uid')->find();
    $openid=$cha['uid'];//openid
    $phone=input('phone');//接收的手机号
    $code=input('code');//接收验证码
    if($code=='')
    {
      return $this->AjaxReturn("-1", "你输入的验证码不正确！");
    }
    else
    {
      //return Cache::get($phone);die;
      //return 'uid'.$openid.'手机号'.$phone.'输入的验证码'.$code.'手机发送的验证码'.Cache::get($phone);;die;
      if(Cache::get($phone)!=$code)
      {
        return $this->AjaxReturn("-1", "你输入的验证码不正确！");
      }
      else
      {
        $add=db('user')->where('uid',$openid)->update(['phone'=>$phone]);
        return $this->AjaxReturn("1", "手机号修改成功！");
      }
    }
  }

  //详情页评论的显示
  public function pinglun()
  {
    //获取当前域名
    $request = Request::instance();
    $domain=$request->domain();
    $mid=input('mid');//接收文章mid
    //$uid=input('uid');//接收文章发布人地uid
    if(!empty($mid))
    {
      $ping=$this->evalutelist($mid);


      if(empty($ping))
      {
        $ping='abcd';
      }
      return $this->AjaxReturn("1","操作成功",$ping);
    }
    else
    {
      return $this->AjaxReturn("-1","未接收到文章mid");
    }
  }
  public function evalutelist($message_id)
  {
    //$message_id=input('message_id');
    //获取当前域名
    $request = Request::instance();
    $domain=$request->domain();
    $evalutelist=Db('evalute')
      ->alias('ev')
      ->join('f_user pj','pj.uid=ev.pjid','left')
      ->join('f_user bp','bp.uid=ev.bpid','left')
      ->where('message_id',$message_id)
      ->where('parent_evalute_id',0)
      //->where('ev.sfig',1)
      ->field('ev.*,pj.uname as pjname,pj.avatars_img as tx,pj.head_portrait as wtx,pj.nickname as pjnickname,bp.uname as bpname,bp.nickname as bpnickname')
      ->select();
    $arr=$evalutelist;
    if(!empty($evalutelist)){
      $ur=$domain.'/upload/portrait/';
      foreach($evalutelist as $k=>$v){
        //return  $arr[$k]['tx'];
        if($v['tx']!='')
        {
          $arr[$k]['tx']=$ur.$v['tx'];
        }
        else
        {
          $arr[$k]['tx']=$v['wtx'];

        }
        if($v['tx'] == '' && $v['wtx'] == '')
        {
          $arr[$k]['tx']=$domain."/upload/linshiimg/20190411095739.jpg";
        }
        if($v['pjname']=='')
        {
          $arr[$k]['pjname']=$v['pjnickname'];
        }
        else
        {
          $arr[$k]['pjname']=$v['pjname'];
        }
        $downevalute=Db('evalute')->where('message_id',$message_id)->where('parent_evalute_id',$v['evalute_id'])->count();
        if($downevalute>0){
          $arr[$k]['down']=$this->getdownevalutes(array(), $message_id, $v['evalute_id']);
        }else{
          $arr[$k]['down']=array();
        }
      }
    }return $arr;
  }
  public function getdownevalutes($arr,$message_id,$parent_evalute_id)
  {
    $downevalute=Db('evalute')
      ->where('message_id',$message_id)
      ->where('parent_evalute_id',$parent_evalute_id)
      ->count();
    if($downevalute>0) {
      $evalute = Db('evalute')
        ->alias('ev')
        ->join('f_user pj','pj.uid=ev.pjid','left')
        ->join('f_user bp','bp.uid=ev.bpid','left')
        ->where('message_id', $message_id)
        ->where('parent_evalute_id',$parent_evalute_id)
        // ->where('ev.sfig',1)
        ->field('ev.*,pj.uname as pjname,pj.nickname as pjnickname,bp.uname as bpname,bp.nickname as bpnickname')
        ->select();
      foreach ($evalute as $k) {
        if($k['pjname']=='')
        {
          $k['pjname']=$k['pjnickname'];
        }
        else
        {
          $k['pjname']=$k['pjname'];
        }
        if($k['bpname']=='')
        {
          $k['bpname']=$k['bpnickname'];
        }
        else
        {
          $k['bpname']=$k['bpname'];
        }
        $arr[] = $k;
        $arr = $this->getdownevalutes($arr, $message_id, $k['evalute_id']);
      }
    }
    return $arr;
  }
  public function AjaxReturn($code,$msg,$data=array())
  {

    $returnData=array(
      "code"=>$code
    );
    if($msg)
    {
      $returnData["message"]=$msg;
    }else
    {
      $returnData["message"]=$this->getErrorInfo($code);
    }
    if(!empty($data))
    {
      $returnData["data"]=$data;
    }
    exit(json_encode($returnData));
  }

  function httpRequest($url, $data='', $method='GET'){
    $curl = curl_init();  
    curl_setopt($curl, CURLOPT_URL, $url);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);  
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);  
    curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);  
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);  
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);  
    if($method=='POST')
    {
      curl_setopt($curl, CURLOPT_POST, 1); 
      if ($data != '')
      {
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);  
      }
    }

    curl_setopt($curl, CURLOPT_TIMEOUT, 30);  
    curl_setopt($curl, CURLOPT_HEADER, 0);  
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);  
    $result = curl_exec($curl);  
    curl_close($curl);  
    return $result;
  } 


  public function getQRCode()
  {
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c1a86ee3e43e4a3&secret=32f54b415ab46d898b2714c327b8d4b9";

    // 创建一个新cURL资源
    $ch  =  curl_init ();

    // 设置URL和相应的选项
    curl_setopt ( $ch , CURLOPT_URL ,  $url );
    curl_setopt ( $ch , CURLOPT_HEADER ,  false );
    curl_setopt ( $ch , CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ( $ch , CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt ( $ch , CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt ( $ch , CURLOPT_SSLVERSION, 1);

    // 抓取URL并把它传递给浏览器
    $str = curl_exec ( $ch );

    //关闭cURL资源，并且释放系统资源
    curl_close ( $ch );
    // echo $str;

    //将str->数组
    $arr = json_decode($str , true);

    //添加新元素
    $arr['create_time'] = time();

    //将数组->json
    $str = json_encode($arr);
    // 获取access_token
    //$access_token = request()->post('access_token');
    // 拼接微信服务端获取二维码需要的url
    $urls = 'https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=' . $arr['access_token'];
    $path = "pages/yemian/mingpian/mingpian?uid=".request()->post('uid');
    $width=430;
    $json='{"path":"'.$path.'","width":'.$width.'}';
    $result = $this->api_notice_increment($urls, $json);
    header('Content-Type: image/jpeg');
    echo $result;
    die;
  }
  public function Base()
  {
    $id=input('id');
    //接收用户uid
    //接收最新的图片
    $image=input('base');
    $base64_string= explode(',', $image);
    //服务器中存放图片的文件夹名称
    $path='qrcoded';
    //生成一个随机数用来生成图片名称
    $rand=rand(1000,9999);
    //生成图片名称
    $pers=$id.'.jpg';
    //文件夹目录$image
    $path ='upload'.DS.$path;
    //文件绝对路径
    $absolute=ROOT_PATH.$path.DS.$pers;
    //判断目录是否存在 不存在就创建
    if (!is_dir(ROOT_PATH.$path))
    {
      mkdir(ROOT_PATH.$path,0777,true);
    }

    $r = file_put_contents($absolute, base64_decode($base64_string[1]));
    if($r){

      return $this->AjaxReturn('1','图片上传成功',$path.DS.$pers);
    }

  }

  public function api_notice_increment($url, $data)
  {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    if (curl_errno($ch)) {
      curl_close($ch);
      return $ch;
    } else {
      curl_close($ch);
      return $tmpInfo;
    }
  }







  public function getXcxCode(){
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx6c1a86ee3e43e4a3&secret=32f54b415ab46d898b2714c327b8d4b9";
    set_time_limit (0);
    $params = [];
    //获取参数值
    //$goods_id = input('uid');
    $store_id = input('uid');
    if(!$store_id){
      return $this->AjaxReturn(2, 'store_id info error');
    }   
    //查询用户信息
    $one_find = db('user')->field('avatars_img,head_portrait')
      ->where('uid='.$store_id)
      ->find();
    if($one_find['avatars_img']!=''){
      $avatarUrl = 'https://www.agrimanu.cn/upload/portrait/'.$one_find['avatars_img'];//用户头像url=
    }elseif($one_find['avatars_img']==''&&$one_find['head_portrait']!=''){
      $avatarUrl = $one_find['head_portrait'];//用户头像url
    }else{
      $avatarUrl = 'https://www.agrimanu.cn/upload/linshiimg/20190411095739.jpg';
    }

    //dump($avatarUrl);die;
    //用户头像图片变圆形
    $avatarUrl = file_get_contents($avatarUrl);
    $logo= $this->yuanImg($avatarUrl);//返回的是图片数据流

    $ch  =  curl_init ();

    // 设置URL和相应的选项
    curl_setopt ( $ch , CURLOPT_URL , $url );
    curl_setopt ( $ch , CURLOPT_HEADER ,  false );
    curl_setopt ( $ch , CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ( $ch , CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt ( $ch , CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt ( $ch , CURLOPT_SSLVERSION, 1);

    // 抓取URL并把它传递给浏览器
    $str = curl_exec ( $ch );

    //关闭cURL资源，并且释放系统资源
    curl_close ( $ch );
    // echo $str;

    //将str->数组
    $arr = json_decode($str , true);

    //添加新元素
    $arr['create_time'] = time();

    //将数组->json
    $str = json_encode($arr);



    //      $wxToken = new Wechat();
    //      $access_token = $wxToken->getAccessToken();
    //      if(!$access_token)
    //          return $this->AjaxReturn(7, 'access_token past due');
    $access_token = $arr['access_token'];

    //不存在，生成二维码
    $url='https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_token;
    $data = [
      'scene'=>$store_id,
      'width'=>430,
      'page'=>'pages/yemian/mingpian/mingpian',
      'auto_color'=>false,
    ];
    $data = json_encode($data);
    $result = $this->_requestPost($url,$data);

    if (!$result){
      return $this->AjaxReturn(4, 'result info error');
    }
    //二维码与头像结合
    $sharePic = $this->qrcodeWithLogo($result,$logo);//return $sharePic;
    $img_tu = ROOT_PATH .'upload/qrcoded/'.$store_id.'.jpg';
    //生成图片二维码
    file_put_contents($img_tu, $sharePic);
    $img_tus = 'https://www.agrimanu.cn/upload/qrcoded/'.$store_id.'.jpg';
    return $this->AjaxReturn(6, 'Img Upload Fail',$img_tus);
  }
  /** 
         * 剪切图片为圆形 
         * @param  $picture 图片数据流 比如file_get_contents(imageurl)返回的东东
         * @return 图片数据流
         */
  function yuanImg($picture) {
    $src_img = imagecreatefromstring($picture);
    $w= imagesx($src_img);
    $h = imagesy($src_img);
    $w  = min($w, $h);
    $h  = $w;
    $img = imagecreatetruecolor($w, $h);
    //这一句一定要有
    imagesavealpha($img, true);
    //拾取一个完全透明的颜色,最后一个参数127为全透明  
    $bg = imagecolorallocatealpha($img, 255, 255, 255, 127);
    imagefill($img, 0, 0, $bg);
    $r  = $w / 2; //圆半径  
    $y_x = $r; //圆心X坐标  
    $y_y = $r; //圆心Y坐标  
    for ($x = 0; $x < $w; $x++) {
      for ($y = 0; $y < $h; $y++) {
        $rgbColor = imagecolorat($src_img, $x, $y);
        if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
          imagesetpixel($img, $x, $y, $rgbColor);
        }
      }
    }
    /**
     * 如果想要直接输出图片，应该先设header。header("Content-Type: image/png; charset=utf-8");
     * 并且去掉缓存区函数
     */
    //获取输出缓存，否则imagepng会把图片输出到浏览器
    ob_start();
    imagepng ( $img );
    imagedestroy($img);
    $contents =ob_get_contents();
    ob_end_clean();
    return $contents;
  }

  function qrcodeWithLogo($QR,$logo){
    $QR = imagecreatefromstring ($QR);
    $logo =imagecreatefromstring ($logo);
    $QR_width = imagesx ( $QR );//二维码图片宽度
    $QR_height = imagesy ( $QR );//二维码图片高度
    $logo_width = imagesx ( $logo );//logo图片宽度
    $logo_height = imagesy ( $logo );//logo图片高度   
    $logo_qr_width = $QR_width / 2.2;//组合之后logo的宽度(占二维码的1/2.2) 
    $scale = $logo_width / $logo_qr_width;//logo的宽度缩放比(本身宽度/组合后的宽度)
    $logo_qr_height = $logo_height / $scale;//组合之后logo的高度 
    $from_width = ($QR_width - $logo_qr_width) / 2;//组合之后logo左上角所在坐标点
    /**
           * 重新组合图片并调整大小 
           * imagecopyresampled() 将一幅图像(源图象)中的一块正方形区域拷贝到另一个图像中 
          */
    imagecopyresampled ($QR,$logo,$from_width,$from_width,0,0,$logo_qr_width,$logo_qr_height,$logo_width,$logo_height );
    /**
           * 如果想要直接输出图片，应该先设header。header("Content-Type: image/png; charset=utf-8");
           * 并且去掉缓存区函数
           */
    //获取输出缓存，否则imagepng会把图片输出到浏览器
    ob_start();
    imagepng ( $QR );
    imagedestroy($QR);
    imagedestroy($logo);
    $contents=ob_get_contents();
    ob_end_clean();
    return $contents;
  }
  protected function _requestPost($url, $data, $ssl=true) {
    //curl完成
    $curl = curl_init();
    //设置curl选项
    curl_setopt($curl, CURLOPT_URL, $url);//URL
    $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '
        Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';
    curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);//user_agent，请求代理信息
    curl_setopt($curl, CURLOPT_AUTOREFERER, true);//referer头，请求来源
    curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时时间
    //SSL相关
    if ($ssl) {
      curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//禁用后cURL将终止从服务端进行验证
      curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//检查服务器SSL证书中是否存在一个公用名(common name)。
    }
    // 处理post相关选项
    curl_setopt($curl, CURLOPT_POST, true);// 是否为POST请求
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// 处理请求数据
    // 处理响应结果
    curl_setopt($curl, CURLOPT_HEADER, false);//是否处理响应头
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//curl_exec()是否返回响应结果

    // 发出请求
    $response = curl_exec($curl);
    if (false === $response) {
      echo '<br>', curl_error($curl), '<br>';
      return false;
    }
    curl_close($curl);
    return $response;
  }
  //实名过期判断修改
  public function changeRflg(){
    $res=db('real')->select();
    $time=date('Y-m-d H:i:s');
    foreach($res as $key=>$value){
      if($res[$key]['rflg']==1){
        if($res[$key]['stoptime']<$time){
          $rs=db('real')->where('rid',$res[$key]['rid'])->update(['rflg'=>3]);
          $ras=db('user')->where('uid',$res[$key]['uid'])->update(['uname'=>""]);
          if($rs || $ras){
            echo '成功';
          }else{
            echo '失败';
          }
        }
      }
    }
  }
}